use crate::db_pool;
use crate::error::{Error, Result};
use crate::model::system_admin::{SystemAdmin, SystemAdminDto, SystemAdminPageDTO, SystemAdminVo};
use crate::utils::password_utils::PasswordUtils;
use rbatis::rbdc::DateTime;
use rbatis::{Page, PageRequest};

pub struct SystemAdminService {}

impl SystemAdminService {
    /// 管理员列表
    pub async fn page(&self, dto: &SystemAdminPageDTO) -> Result<Page<SystemAdminVo>> {
        let system_admin_page = SystemAdmin::select_page(
            db_pool!(),
            &PageRequest::from(dto),
            dto.nickname.as_deref().unwrap_or_default(),
            dto.account.as_deref().unwrap_or_default(),
        )
        .await?;
        let page = Page::<SystemAdminVo>::from(system_admin_page);
        Ok(page)
    }

    /// 管理员详情
    pub async fn detail(&self, user_id: u32) -> Result<SystemAdminVo> {
        let system_admin = SystemAdmin::select_by_column(db_pool!(), "id", user_id)
            .await?
            .into_iter()
            .next()
            .ok_or_else(|| Error::from("user_cannot_find"))?;
        Ok(SystemAdminVo::from(system_admin))
    }

    /// 创建管理员
    pub async fn create(&self, data: SystemAdmin) -> Result<String> {
        let password = data.password.unwrap_or_default();
        let salt = PasswordUtils::create_salt();
        let raw_password = PasswordUtils::encode(&password, &salt);
        let model = SystemAdmin {
            id: None,
            nickname: data.nickname,
            avatar: None,
            account: data.account,
            password: raw_password.into(),
            salt: salt.into(),
            mobile: data.mobile,
            is_delete: Some(0),
            is_disable: Some(0),
            create_time: Some(DateTime::now()),
            update_time: Some(DateTime::now()),
            delete_time: None,
        };
        match SystemAdmin::insert(db_pool!(), &model).await {
            Ok(_v) => Ok("创建成功！".to_string()),
            Err(e) => Err(Error::E(e.to_string())),
        }
    }

    /// 管理员信息更新
    pub async fn update(&self, dto: SystemAdminDto) -> Result<u64> {
        let _ = SystemAdmin::select_by_column(db_pool!(), "id", &dto.id.as_ref())
            .await?
            .into_iter()
            .next()
            .ok_or_else(|| Error::from("user_cannot_find"))?;
        let dto = SystemAdmin::from(dto);
        Ok(SystemAdmin::update_by_column(db_pool!(), &dto, "id")
            .await?
            .rows_affected)
    }

    /// 管理员删除
    pub async fn delete(&self, user_id: u32) -> Result<u64> {
        let mut system_admin = SystemAdmin::select_by_column(db_pool!(), "id", user_id)
            .await?
            .into_iter()
            .next()
            .ok_or_else(|| Error::from("user_cannot_find"))?;
        system_admin.is_delete = 1.into();
        Ok(
            SystemAdmin::update_by_column(db_pool!(), &system_admin, "id")
                .await?
                .rows_affected,
        )
    }
    /// 获取管理员信息
    pub async fn info(&self, user_id: &u32) -> Result<SystemAdminVo> {
        let system_admin_info = SystemAdmin::select_by_column(db_pool!(), "id", user_id)
            .await?
            .into_iter()
            .next();
        Ok(SystemAdminVo::from(system_admin_info.unwrap_or_default()))
    }
}
